package net.ge.mosq.utils;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import net.ge.mosq.Constants;
import net.ge.mosq.Constants.Entities;
import net.ge.mosq.jdo.entity.AccountType;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.google.appengine.api.datastore.Entity;

/**
 * @author noodles.wumu@gmail.com
 * @since 2012/07/31 11:18:07
 * @version 1.0
 */
public class Utils implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6597809570321356782L;

	public static String getProperty(Key key) {
		ResourceBundle rb = ResourceBundle.getBundle("configuration");
		return rb.getString(key.toString());
	}

	public enum Key {
		ATT_FOLDER_PATH("AttFolderPath"), SENDER_USERNAME("SenderUserName"), SENDER_PASSWORD("SenderPassWord"), SUBJECT_PREFIX("SubjectPrefix"), MAILTO_ADDRESS("MailToAddress"), ACCOUNT_FILE_PATH(
				"AccountFilePath");
		private String key_;

		private Key(String key) {
			this.key_ = key;
		}

		@Override
		public String toString() {
			return this.key_;
		}
	};

	public enum Atts {
		DEFUALT_ACC_TEMPLATE("defualtAccTemplate"), ACCOUNT_TYPES("accountTypes"), DISPATCH_PATTERN("despatchPattern");

		private String key_;

		private Atts(String key) {
			this.key_ = key;
		}

		@Override
		public String toString() {
			return this.key_;
		}
	};

	public static List<Entity> getAccItemsTemplate(String path) {
		List<Entity> accountList = new ArrayList<Entity>();

		try {
			DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document document = db.parse(path);
			NodeList nodeList = document.getElementsByTagName(Entities.ACCOUNT.toString());
			for (int i = 0; i < nodeList.getLength(); i++) {
				NamedNodeMap nnm = nodeList.item(i).getAttributes();
				Entity accountEntity = new Entity(Entities.ACCOUNT.toString());
				accountList.add(accountEntity);
				for (int j = 0; j < nnm.getLength(); j++) {
					accountEntity.setProperty(nnm.item(j).getNodeName(), nnm.item(j).getNodeValue());
				}
			}
		} catch (ParserConfigurationException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
		}
		return accountList;
	}

	public static Map<String, AccountType> getAllAcountType(String path) {
		Map<String, AccountType> accountTypes = new HashMap<String, AccountType>();
		try {
			DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document document = db.parse(path);
			NodeList nodeList = document.getElementsByTagName("type");
			for (int i = 0; i < nodeList.getLength(); i++) {
				NamedNodeMap nnm = nodeList.item(i).getAttributes();
				for (int j = 0; j < nnm.getLength(); j++) {
					accountTypes.put(nnm.getNamedItem("name").getNodeValue(), new AccountType(nnm.getNamedItem("name").getNodeValue(), nnm.getNamedItem("label1").getNodeValue(),
							nnm.getNamedItem("label2").getNodeValue(), nnm.getNamedItem("belong").getNodeValue()));
				}
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return accountTypes;
	}

	public static Map<String, String> getDispatchPattern(String path) {
		Map<String, String> DispatchPatterns = new HashMap<String, String>();
		try {
			DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document document = db.parse(path);
			NodeList nodeList = document.getElementsByTagName(Entities.DISPATCHPATTREN.toString());
			for (int i = 0; i < nodeList.getLength(); i++) {
				NamedNodeMap nnm = nodeList.item(i).getAttributes();
				nnm.item(1).getNodeValue();
				for (int j = 0; j < nnm.getLength(); j++) {
					DispatchPatterns.put(nnm.getNamedItem("src").getNodeValue(), nnm.getNamedItem("dispatch").getNodeValue());
				}
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return DispatchPatterns;
	}

	/**
	 * <p>
	 * Look up and return current user locale, based on the specified parameters.
	 * </p>
	 * 
	 * @param request
	 *            The request used to lookup the Locale
	 * @param locale
	 *            Name of the session attribute for our user's Locale. If this is <code>null</code>, the default locale key is used for the lookup.
	 */
	public static Locale getUserLocale(HttpServletRequest request) {

		Locale userLocale = null;
		HttpSession session = request.getSession(false);

		// Only check session if sessions are enabled
		if (session != null) {
			userLocale = (Locale) session.getAttribute(Constants.USER_LOCALE);
		}

		if (userLocale == null) {
			// Returns Locale based on Accept-Language header or the server default
			userLocale = request.getLocale();
		}

		return userLocale;
	}
}
